import { count } from "console";
import { catchError, delay, interval, map, mergeMap, of, retry } from "rxjs";

export function retryDemo() {
  const interVob = interval(1000);

  interVob
    .pipe(
      mergeMap((val) => {

        if (val > 3) {
          return catchError(() => {
            return "error";
          });
        }

        return of(1111);
      }),

      retry({
        count: 2,
        delay: 5000,
      }), // 可以把上面的程序重新执行两次, 每次重复执行的时候，等5s
    )
    .subscribe({
      next(v) {
        console.log(v);
      },
      error(err) {
        console.log(typeof err);
      },
    });
}

export function catchErrorDemo() {
  of(1, 2, 3, 4, 5)
    .pipe(
      map((x) => {
        if (x === 4) {
          throw new Error("不能为4");
        }

        return x;
      }),
      catchError((err) => {
        // 当遇到错误�时候，打印错误并给出默认处理方式，返回一个Obserable
        console.log(err);

        // return of(888);
        throw new Error("this is error");
      }),
    )
    .subscribe({
      next: (x) => console.log(x),
      error(e) {
        // 打印 catchError 抛出来的异常;
        console.log(e);
      },
    });
}
